// appalachianCommands.js

var AppalachianCommands = {};

AppalachianCommands.showWelcome = function() {
	window.open("chrome://appalachian/content/welcome.xul", "appalachian-welcome", "chrome=yes,modal=yes,resizable=yes,width=400,height=400");
}

AppalachianCommands.showIdManager = function() {
	window.open("chrome://appalachian/content/id-manager.xul", "appalachian-id-manager", "chrome=yes,modal=yes,resizable=yes,width=600,height=400");
};

AppalachianCommands.showPreferences = function() {
	window.open("chrome://appalachian/content/preferences.xul", "appalachian-preferences", "chrome=yes,modal=yes,resizable=yes,width=300,height=300");
};

AppalachianCommands.useID = function(id, field, formRef) {
	// fill in and submit when id is selected
	if (!field) field = 'openid_url';
	var stringBundle = document.getElementById("appalachian-bundle");
	var inputs;
	if (!formRef) {
		inputs = content.document.getElementsByName(field);
	} else {
		inputs = [ content.document.forms[formRef].wrappedJSObject.elements[field] ];
	}

	if (inputs.length == 1) {
		inputs[0].value = AppalachianDB.getInfo(id).getURL();
		if (!formRef) {
			var formParent = inputs[0].form;
			for (var j = 0; j < content.document.forms.length; j++) {
				if (content.document.forms[j] == formParent) {
					formRef = j;
					break;
				}
			}
		}
		Appalachian.getState().storeUse(id, content.document.location.href, field, formRef, inputs[0].form.method, inputs[0].form.action);
		Appalachian.getState().advance(APPALACHIAN_ACTION_CLICK);
		inputs[0].form.submit();
	} else if (inputs.length != 1) {
		if (content.document.forms.length > 0) {
			var focused = document.commandDispatcher.focusedElement;
			if (!focused) {
				var fieldmsg = stringBundle.getString("clickfield");
				alert(fieldmsg);
				return;
			}
			if (focused.type != 'text') {
				var fieldmsg = stringBundle.getString("nontextfield");
				alert(fieldmsg);
				return;
			}
			focused.blur();
			focused.value = AppalachianDB.getInfo(id).getURL();
			var formParent = focused.form;
			for (var j = 0; j < content.document.forms.length; j++) {
				if (content.document.forms[j] == formParent) {
					formRef = j;
					break;
				}
			}
			Appalachian.getState().storeUse(id, content.document.location.href, focused.name, formRef, focused.form.method, focused.form.action);
			Appalachian.getState().advance(APPALACHIAN_ACTION_CLICK);
			focused.form.submit();
		} else {
			return;
		}
	}

};

AppalachianCommands.automateAction = function() {
	// has the plug-in been initialized?  open up the manager if not
	var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
	var init = prefs.getBoolPref("extensions.appalachian.initialized");
	var defaultID = prefs.getIntPref("extensions.appalachian.defaultID");
	var defaults = prefs.getBoolPref("extensions.appalachian.useDefault");
	// @@ init here?
	if (!init) {
		AppalachianCommands.showWelcome();
		return;
	}

	// if openid.server is a link rel, pop up add box with url as id
	var links = content.document.getElementsByTagName('link');
	for (var i = 0; i < links.length; i++) {
		if (links[i].hasAttribute("rel") && links[i].getAttribute("rel").indexOf("openid.server") != -1) {
			if(!AppalachianDB.exists(content.document.location.href)) {
				Appalachian.getState().advance(APPALACHIAN_ACTION_CLICK);
				window.openDialog("chrome://appalachian/content/add-openid.xul", "appalachian-add-openid", "chrome,modal", { url : content.document.location.href , server : links[i].getAttribute("href"), saved : function() { Appalachian.getState().advance(APPALACHIAN_ACTION_SAVE) }, cancelled: function() { Appalachian.getState().advance(APPALACHIAN_ACTION_ABORT) } } );
				return;
			} else {
				var stringBundle = document.getElementById("appalachian-bundle");
				var alreadymsg = stringBundle.getString("alreadyexists");
				alert(alreadymsg);
			}
		}
	}

	// try doing a yadis thing
	if (Appalachian.getState().getCurrentState() == "addavailable") {
		var ylib = new Yadis(content.document.location.href);
		Appalachian.getState().advance(APPALACHIAN_ACTION_CLICK);
		window.openDialog("chrome://appalachian/content/add-openid.xul", "appalachian-add-openid", "chrome,modal", { url : content.document.location.href , server : ylib.getAuthorities(content.document), saved : function() { Appalachian.getState().advance(APPALACHIAN_ACTION_SAVE) }, cancelled: function() { Appalachian.getState().advance(APPALACHIAN_ACTION_ABORT) } } );
		return;
	}

	var loc = content.document.location.href;
	var ids = AppalachianDB.listUsesIds(loc);
	if (ids.length == 1) {
		// if requestor is familiar, only one id associated,
		// fill in and submit
		AppalachianCommands.useID(ids[0].openid, ids[0].field, ids[0].form);
	} else if (ids.length > 1) {
		// if requestor is familiar and several ids,
		// popup id selection menu; submit on selection
		var openids = new Array();
		for (var k = 0; k < ids.length; k++) {
			openids.push(AppalachianDB.getInfo(ids[k].openid));
		}
		AppalachianCommands.addIDs("appalachian-status-id-selection-menu", openids, true);
		var menu = document.getElementById("appalachian-status-id-selection-menu");
		menu.showPopup(document.getElementById("appalachian-status-icon"), -1, -1, "popup");
	} else if (ids.length == 0 && defaults && defaultID > 0 ) {
		// if requestor is unknown, fill in default
		AppalachianCommands.useID(defaultID, null, null);
	} else if (ids.length == 0 && !defaults) {
		AppalachianCommands.addIDs("appalachian-status-id-selection-menu", null, true);
		var menu = document.getElementById("appalachian-status-id-selection-menu");
		menu.showPopup(document.getElementById("appalachian-status-icon"), -1, -1, "popup");		
	} else {
		AppalachianCommands.showWelcome();
		return;
	}
};

AppalachianCommands.addIDs = function(menu, ids, explain) {
	var m = document.getElementById(menu);
	for (var i = m.childNodes.length; i > 0; i--) {
		var n = m.childNodes[i-1];
		if (n.id && n.id.indexOf(menu + "-openid-") == 0)
			m.removeChild(n);
	}

	var marker = m.firstChild;
	if (!ids) ids = AppalachianDB.listAll();
	var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
	var defaultid = prefs.getIntPref("extensions.appalachian.defaultID");
	var defaults = prefs.getBoolPref("extensions.appalachian.useDefault");
	if (ids.length == 0) {
		AppalachianCommands.showIdManager();
		return;
	}
	for (var i = 0; i < ids.length; i++) {
		var id = ids[i];
		var item = document.createElement("menuitem");
		var label = id.getUse();
		if (defaults)
			label += (id.getID() == defaultid) ? " (default)" : "";
		item.setAttribute("id", menu + "-openid-" + id.getID());
		item.setAttribute("label", label);
		item.setAttribute("oncommand", "AppalachianCommands.useID(" + id.getID() + ",null,null);");
		m.insertBefore(item, marker);
	}
	if (explain) {
		var exp = document.createElement("menuitem");
		var explabel = "Choose your OpenID";
		exp.setAttribute("id", menu + "-openid-explain");
		exp.setAttribute("label", explabel);
		exp.setAttribute("disabled", true);
		m.insertBefore(exp, m.firstChild);
	}
};

// continuation for API use
AppalachianCommands.apiLogin = false;
